<template>
	<view class="content">
		<scroll-view class="scroll-view">
			<view>
				<text class="type">{{info.type}} 第{{curIndex+1}}题</text>
			</view>
			<view v-if="info.type == '填空题'">
				<view>
					<view class="html-style">
						<text>{{getAskContent()}}</text>
					</view>
					<view v-for="(item, index) in askInputData()" :key="index">
						<input :placeholder="'请输入您的答案'+(index+1)" :key="curIndex" v-model="askInputData()[index]"
							style="margin-top: 20rpx;" />
					</view>
				</view>
			</view>
			<view v-if="showAnalyse" class="analyse-view">
				<view class="analyse-tip">答案与解析</view>
				<text class="analyse-answer">{{getAnswers()}}</Text>
			</view>
		</scroll-view>
		<view style="position: absolute;width: 500rpx;top: 700rpx;left: 100rpx;">
			<button style="margin-top: 40rpx;" :class="getPrevCls" @click="getPrev">上一题</button>
			<button style="margin-top: 20rpx;" :class="getNextCls" @click="getNext(1)">下一题</button>
			<button style="margin-top: 20rpx;" :class="getNextCls" @click="getNext(2)">跳过此题</button>
		</view>
		<view class="fab" @click="clickShowCardModal">
			<text style="color: white; font-size: 25rpx;position: absolute;left: 25rpx;top:40rpx;">答题卡</text>
		</view>
		<view class="bottom">
			<button v-if="type != 2" class="button" :class="getAnalyseCls" @click="getAnalyse">查看解析</button>
			<button class="button" :class="getCollectCls" @click="collect">{{getCollectText}}</button>
			<button v-if="type == 2" class="button" @click="getScantron">{{getCurrentTotalLabel()}}</button>
		</view>
		<view class="overlay" v-if="showCardModal" @click="hideModal"></view>
		<timu-card class="timu-card" v-if="showCardModal" :curIndex="curIndex-1" :list="askData" :isAnalyse="type"
			@choose="chooseTimu" @handlePaper="handlePaper" @menuClick="menuClick"></timu-card>
	</view>
</template>

<script>
	import Config from '@/config/config.js'
	import TimuCard from './timucard.vue';
	import MockData from '@/mockdata/mockdata.js'
	import _ from 'lodash';
	export default {
		components: {
			TimuCard
		},
		data() {
			return {
				curIndex: 0,
				questionData: [],
				backupArray: [],
				inputName: '',
				total: 10,
				list: [],
				newlist: [], // 将list按一行显示count个数转换
				count: 6, // 答题卡一行显示题数
				info: {
					type: '填空题'
				},
				paperId: '',
				type: '',
				doModel: '',
				askList: [],
				currentAnswers: [], // 当前题目的回答
				showAnalyse: false, // 是否为题目解析
				viewImages: [],
				tip: '', // 提示文本，需手动切换下一题
				showModal: false,
				showCardModal: false,
				showImageModal: false,
				showMultiChoiceTip: false, // 多选题提示
				showUncertainChoiceTip: false, // 不定项选择题提示
				isFetchScantron: false, // 是否已经获取了答题卡接口，新版接口出来后修改为false
				hasChoosed: true,
				isAnalyse: false,
				askData: [],
				modalSetting: {
					type: 0,
					content: '请再次确认是否退出登录？'
				},
				wrongArray: []
			}
		},
		onUnload: () => { //离开页面清除输入框内容
			const inputData = MockData['miTimus']
			inputData.forEach(i => {
				i.inputNum.forEach((element, index, array) => {
					if (typeof element === "string") {
						array[index] = "";
					}
				});
			})
		},
		onLoad(e) {
			this.type = e.index;
			if (e.index == 1) {
				let array = _.cloneDeep(MockData['miTimus'])
				this.askData = this.shuffleArray(array);
			} else if (e.index == 2) {
				let array = _.cloneDeep(MockData['miTimus'])
				for (let i = 0; i < 20; i++) {
					const randomIndex = Math.floor(Math.random() * array.length);
					this.askData.push(array.splice(randomIndex, 1)[0]);
				}
			} else {
				this.askData = MockData['miTimus'];
			}
			uni.setNavigationBarTitle({
				title: e.name || ''
			});
			this.load();
		},
		computed: {
			getName() {
				return this.info.name ? this.info.name.replace(/^\d*\./, '')
					.replace(/^\d*、/, '').replace(/^\d*．/, '').replace(/^\d*\s/, '') : '';
			},
			getAnalyseCls() {
				return !this.showAnalyse[this.curIndex - 1] ? 'button-disabled' : '';
			},
			getCollectText() {
				return this.info.collected ? '已收藏' : '收藏';
			},
			getCollectCls() {
				return !this.info.collected ? 'button-disabled' : '';
			},
			getPrevCls() {
				return this.curIndex == 0 ? 'button-disabled_' : '';
			},
			getNextCls() {
				return this.curIndex == this.askData.length - 1 ? 'button-disabled_' : '';
			}
		},
		methods: {
			getCurrentTotalLabel() {
				return '交卷 ' + (this.curIndex + 1) + '/' + this.askData.length;
			},
			getAskContent() {
				return this.askData[this.curIndex].ask;
			},
			askInputData() {
				return this.askData[this.curIndex].inputNum;
			},
			getAnswers() {
				let answer = this.askData[this.curIndex].question;
				if (answer && answer instanceof Array) answer = answer.join('    ');
				return answer || '';
			},
			shuffleArray(array) {
				for (let i = array.length - 1; i > 0; i--) {
					let j = Math.floor(Math.random() * (i + 1));
					// 交换元素
					let temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
				return array;
			},
			clickShowCardModal() {
				this.showCardModal = !this.showCardModal;
			},
			load(id) {
				this.getTimuList(id);
			},
			onQuestionInput(event) {
				this.questionData.push(event.target.value);
			},
			getTimuList(id) {
				this.getTimu(id);
			},
			getTimu(id, index) {},
			convertAnswers(list) {
				let currentAnswers = [];
				for (let i in list) {
					let data = list[i];
					let myAnswer = data.myAnswer;
					currentAnswers.push(myAnswer);
				}
				this.currentAnswers = currentAnswers || [];
			},
			getChoiceText(choice, key) {
				if (key) {
					let choiceText = choice[key];
					if (choiceText.indexOf(key.toUpperCase() + '.') != 0 &&
						choiceText.indexOf(key.toUpperCase() + '、') != 0 &&
						choiceText.indexOf(key.toUpperCase() + ' ') != 0 &&
						choiceText.indexOf(key.toUpperCase() + '．') != 0) {
						choiceText = key.toUpperCase() + '. ' + choice[key];
					}
					return choiceText;
				}
				return '';
			},
			getImgChoiceText(choice, key) {
				return key.toUpperCase() + '. ';
			},
			getAnalyse() {
				this.showAnalyse = !this.showAnalyse;
			},
			collect() { //收藏
				const collectTimu = uni.getStorageSync('collect_timu');
				if (collectTimu.length > 0) {
					let arr = collectTimu;
					const isIndex = arr.find(item => item.index == this.curIndex)
					if (!isIndex) {
						arr.push(this.askData[this.curIndex])
						uni.setStorageSync("collect_timu", arr);
						uni.showToast({
							title: '已收藏，请前往首页查看【已收藏题目】',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '本题已被收藏',
							icon: 'none'
						});
					}
				} else {
					let arr = [];
					arr.push(this.askData[this.curIndex])
					uni.setStorageSync("collect_timu", arr);
					uni.showToast({
						title: '已收藏，请前往首页查看【已收藏题目】',
						icon: 'none'
					});
				}
			},
			getPrev(isSlip) {
				this.showAnalyse = false;
				if (this.curIndex == 0) {
					if (isSlip) {
						uni.showToast({
							title: '已是第一题哦~',
							icon: 'none'
						});
						return;
					}
				}
				this.curIndex = this.curIndex - 1
			},
			getNext(isSlip) {
				this.showAnalyse = false;
				if (this.askData.length - 1 == this.curIndex) {
					uni.showToast({
						title: '已是最后一题哦~',
						icon: 'none'
					});
					return;
				}
				if (isSlip == 2) return this.curIndex = this.curIndex + 1
				if (this.tipsWrong()) return
				this.curIndex = this.curIndex + 1
			},
			tipsWrong() { //错题提示
				for (let i = 0; i < Math.min(this.askData[this.curIndex].inputNum.length, this.askData[this.curIndex].answer
						.length); i++) {
					let combinedRegex = /[\s^\w\s]/g;
					let inputName = this.askData[this.curIndex].inputNum[i].replace(combinedRegex, "");
					let answer = this.askData[this.curIndex].answer[i].replace(combinedRegex, "");

					if (this.askData[this.curIndex].inputNum[i] && (inputName !== answer)) {
						if (this.type == 2) {
							this.setWrongQuestion()
						} else {
							uni.showToast({
								title: `答案${i+1}错误，应为：${this.askData[this.curIndex].answer[i]}`,
								icon: 'none'
							})
						}
						if (this.type != 2) return true
					}
				}
				return false
			},
			setWrongQuestion() { //考试模拟下将错题收集
			this.wrongArray.push(this.askData[this.curIndex])
			return;
				const wrongQuestion = uni.getStorageSync('wrong_question');
				if (wrongQuestion.length > 0) {
					this.wrongArray = wrongQuestion;
					const isIndex = this.wrongArray.find(item => item.index == this.curIndex)
					if (!isIndex) {
						this.wrongArray.push(this.askData[this.curIndex])
					}
				} else {
					this.wrongArray = [];
					
				}
			},
			getAnswer() {
				return this.currentAnswers;
			},
			showCard() {
				this.showModal = true;
				this.showCardModal = true;
			},
			hideModal() {
				this.showModal = false;
				this.showCardModal = false;
			},
			getScantron() {
				if (this.tipsWrong()) return
				this.showCard();
			},
			chooseTimu(index) {
				this.getTimu(index);
				this.showModal = false;
				this.showCardModal = false;
			},
			menuClick(index) {
				this.showAnalyse = false;
				this.showModal = false;
				this.showCardModal = false;
				if (this.tipsWrong()) return
				this.curIndex = index;
			},
			handlePaper(item) {
				this.showCardModal = false;
				let uniqueArray = Array.from(new Set(this.wrongArray.map(item => item.index))).map(id => {
					return this.wrongArray.find(item => item.index === id);
				});
				uni.showModal({
					title: '提示',
					content: `已做题目数：${item.doneTimu.length}   未做题目数：${item.undoTimu.length}  错误题目数：${uniqueArray.length}`,
					success: (res) => {
						if (res.confirm) {
							const timestamp = Date.now();
							const formattedTime = this.formatTime(timestamp);
							const wrongQuestion = uni.getStorageSync('wrong_question');
							let arrayIndex = 1
							let array = [] 
							if (wrongQuestion.length > 0) {
								arrayIndex = (wrongQuestion.length + 1)
								array = [...wrongQuestion]
							}else{
								array = [] 
							}
							console.log(JSON.stringify(array))
							array.push({
								index: arrayIndex,
								time: formattedTime,
								data: uniqueArray
							});
							uni.setStorageSync("wrong_question", array);
							uni.showToast({
								title: '考试结束，前往错题库查看错题记录',
								icon: 'none'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			formatTime(timestamp) {
				const date = new Date(timestamp);
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${month}月${day}日 ${hours}:${minutes}`;
			},
			goLogin() {
				uni.navigateTo({
					url: '/pages/account/login'
				});
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	.scroll-view {
		width: calc(100% - 60rpx);
		margin: 0 30rpx 60rpx 30rpx;
	}

	.type {
		font-size: 32rpx;
		color: #29B581;
	}

	.title {
		font-size: 32rpx;
		color: #1a1a1a;
		line-height: 40rpx;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}

	.question-text {
		font-size: 32rpx;
		color: #29B581;
		height: 40rpx;
		margin-top: 10rpx;
	}

	.html-style {
		margin: 20rpx;
		background-color: #FFFFFF;
	}

	.choice-text {
		font-size: 32rpx;
		color: #1a1a1a;
		line-height: 40rpx;
		margin-top: 10rpx;
		margin-bottom: 10rpx
	}

	.select-choice-text {
		color: #ed675a;
	}

	.input {
		font-size: 32rpx;
		color: #1a1a1a;
		height: 88rpx;
		padding: 6rpx;
		border-color: #e2e3e4;
		border-width: 1rpx;
		border-radius: 1rpx;
	}

	.analyse-view {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}

	.analyse-tip {
		font-size: 32rpx;
		color: #ed675a;
		height: 40rpx;
		margin-bottom: 20rpx;
	}

	.analyse-answer {
		font-size: 32rpx;
		height: 40rpx;
		color: #ed675a;
		width: calc(100% - 40rpx);
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		padding-right: 20rpx;
	}

	.bottom {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		height: 100rpx;
		border-top-color: #F8F8F8;
		border-top-width: 2rpx;
		border-top-style: solid;
		position: fixed;
		bottom: 0;
		background-color: #ffffff;
	}

	.button {
		width: 100%;
		height: 100%;
		font-size: 30rpx;
		color: #ffffff;
		border: none;
		border-style: none;
		background-color: #ed675a;
	}

	.button::after {
		border: none;
	}

	.button-disabled_ {
		color: #999999;
	}

	.button-disabled {
		color: #ffffff;
		font-size: 30rpx;
	}

	.recorrect-button {
		margin: 40rpx;
		color: #999999;
	}

	.overlay {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		background-color: #000000;
		opacity: 0.5;
	}

	.timu-card {
		position: fixed;
		width: 100%;
		height: 824rpx;
		left: 0;
		bottom: 0;
		background-color: #ffffff;
		z-index: 10;
	}

	.selectChoiceText {
		color: #29B581;
	}

	.choice-img-view {
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.fab {
		width: 120rpx;
		height: 120rpx;
		background-image: linear-gradient(to bottom, #8fb32b, #166b44);
		box-shadow: 0px 4rpx 20rpx 0px #999999;
		position: absolute;
		right: 30rpx;
		bottom: 130rpx;
		border-radius: 60rpx;
		flex-direction: column;
	}
</style>